//
//  CXEmotionKeyboard.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/28.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

let CXEmotionViewCellID = "emotionviewcell"

class CXEmotionKeyboard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 工具条
    private lazy var toolBarView: CXEmotionBar = {
        let toolbar = CXEmotionBar(frame: CGRectZero)
        toolbar.delegate = self
        return toolbar
    }()
    /// 表情键盘视图
    private lazy var emotionView: UICollectionView = {
    
        let collectionV = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        let flowlayout = collectionV.collectionViewLayout as! UICollectionViewFlowLayout
        //这个时候设置itemsize 除了使用直接尺寸外没有更好的解决办法 因此把设置放到layoutSubview中
        flowlayout.minimumLineSpacing = 0
        flowlayout.scrollDirection = .Horizontal
        
        collectionV.showsHorizontalScrollIndicator = false
        collectionV.dataSource = self
        collectionV.delegate = self
        collectionV.showsVerticalScrollIndicator = false
        collectionV.pagingEnabled = true
        //设置表情视图的背景颜色为无 为了显现主界面的背景颜色
        collectionV.backgroundColor = UIColor.clearColor()
        collectionV.bounces = false
        
        collectionV.registerClass(CXEmotionViewCell.self, forCellWithReuseIdentifier: CXEmotionViewCellID)
        return collectionV
    }()
    /// 显示页数
    private lazy var pageView: UIPageControl = {
        let pageview = UIPageControl()
        //利用KVC修改私有属性
        pageview.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKeyPath: "_currentPageImage")
        pageview.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKeyPath: "_pageImage")
        //让它不能点击
        pageview.userInteractionEnabled = false
        return pageview
    }()
    
}
// MARK: - 设置UI, 数据源方法
extension CXEmotionKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    private func setupUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(toolBarView)
        addSubview(emotionView)
        addSubview(pageView)
        
        toolBarView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self)
            make.height.equalTo(37)   //因为背景图片的高度换算成 1x 就是37
        }
        emotionView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.top.equalTo(self)
            make.bottom.equalTo(toolBarView.snp_top)
        }
        pageView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(emotionView) //让页码显示看起来好像在表情视图里面
            make.centerX.equalTo(emotionView)
        }
        ///  让一开始的时候，表情视图就滚动到指定section，同时页码指示器也指示对应的页数
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            //通过主队列异步，可以准确的获取到界面显示那一刻表情视图的indexpath
            let indexpath = NSIndexPath(forItem: 0, inSection: 1)
            self.emotionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: false)
            self.setupPageControl(indexpath)
            self.toolBarView.buttonSelect(1)
        }
        
    }
    ///  在布局中设置 collectionViewCell 的itemSize
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let flowlayout = emotionView.collectionViewLayout as! UICollectionViewFlowLayout
//        flowlayout.itemSize = CGSize(width: self.frame.width, height: self.frame.height - toolBarView.frame.height)
        //更好的设置办法
        flowlayout.itemSize = emotionView.bounds.size
    }
    
    // MARK: - 数据源方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CXEmotionTools.sharedTool.allEmotions.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CXEmotionTools.sharedTool.allEmotions[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXEmotionViewCellID, forIndexPath: indexPath) as! CXEmotionViewCell
        cell.emotions = CXEmotionTools.sharedTool.allEmotions[indexPath.section][indexPath.item]
//        print(cell.emoticons.count)
        cell.indexPath = indexPath
        return cell
    }
    ///  在滚动过程中切换toolBar的标签
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let cells = emotionView.visibleCells()
        var indexPath: NSIndexPath?
        if cells.count == 2 {
            
            let cell1 = cells.first!
            let cell2 = cells.last!

            let cell: UICollectionViewCell = fabs(cell1.frame.origin.x - emotionView.contentOffset.x) <= emotionView.bounds.width * 0.5 ? cell1 : cell2
            indexPath = emotionView.indexPathForCell(cell)
        } else {
            indexPath = emotionView.indexPathForCell(cells.first!)
        }
        toolBarView.buttonSelect(indexPath!.section)
        setupPageControl(indexPath!)
    }
    ///  设置pageControl的页码 页数
    private func setupPageControl(indexpath: NSIndexPath) {
        
        pageView.numberOfPages = CXEmotionTools.sharedTool.allEmotions[indexpath.section].count
        pageView.currentPage = indexpath.item
        //TODO: - 当section 的时候，就不必显示分页器了, 这一步判断之后需要修改
        pageView.hidden = indexpath.section == 0
    }
}

extension CXEmotionKeyboard: CXEmotionBarDelegate {
    
    func emotionBarButtonDidClick(button: UIButton, type: CXEmoticonType) {
        //根据按钮的 type 切换到collectionView的不同的section
        let indexpath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        emotionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: true)
        //更新页码
        setupPageControl(indexpath)
    }
}
